<template>
  <s-layout class="wallet-wrap" title="礼品">
    <view
      class="bg-white address-box ss-m-b-14 ss-r-b-10"
      @tap="onSelectAddress"
    >
      <s-address-item :item="ressInfo" :hasBorderBottom="false">
        <view class="ss-rest-button"><text class="_icon-forward"></text></view>
      </s-address-item>
    </view>
    <!-- 商品 -->
    <view
      style="
        background-color: #fff;
        margin-bottom: 14rpx;
        padding: 10rpx;
        font-weight: 700;
      "
      >您可以选择{{ maxSelection }}件商品</view
    >
    <view class="list" v-for="(item, index) in mylist" :key="index">
      <!-- 左  -->
      <view>
        <img
          style="width: 150rpx; height: 160rpx"
          :src="item.albumPics"
          alt=""
        />
      </view>
      <!-- 又 -->
      <view
        style="
          width: 70%;
          height: 200rpx;
          display: flex;
          flex-flow: column;
          justify-content: space-around;
        "
        ><view style="font-size: 26rpx">{{ item.name }}</view>
        <view style="font-size: 22rpx; color: gray">规格默认规格</view>
        <view style="display: flex; justify-content: space-between">
          <span
            >金额:<span style="color: red">￥{{ item.price }}</span>
          </span>
          <checkbox
            :value="String(item.id)"
            :checked="selected.includes(item.id)"
            @click="toggleSelection(item.id)"
            :disabled="isDisabled(item.id)"
        /></view>
      </view>
    </view>
    <!-- 确定 -->
    <view class="btnbox">
      <view class="btn" @click="btn">确定 </view>
    </view>
  </s-layout>
</template>
<script setup>
import { computed, watch, reactive, ref } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import dayjs from "dayjs";
import _ from "lodash";
import { isEmpty } from "lodash";

const itemId = ref(null);

const Id = ref();
const maxSelection = ref(); // 最多可以选择的项数
// 使用 onMounted 钩子获取查询参数
onLoad((query) => {
  itemId.value = query.bookId;
  maxSelection.value = query.num;
  Id.value = query.id;
  getUserScoreBookProduct(query.Id);
  changeConsignee();
});

const ressInfo = ref({});
// 更改
function onSelectAddress() {
  uni.$once("SELECT_ADDRESS", (e) => {
    changeConsignee(e.addressInfo);
  });
  sheep.$router.go("/pages/user/address/list");
}

// 更改收货人地址&计算订单信息
async function changeConsignee(addressInfo = {}) {
  console.log(isEmpty(addressInfo), "地址");
  if (isEmpty(addressInfo)) {
    const res = await sheep.$api.user.address.default({});
    ressInfo.value = res;
  }
  if (!isEmpty(addressInfo)) {
    ressInfo.value = addressInfo;
  }
}

const mylist = ref();
const getUserScoreBookProduct = async (id) => {
  console.log(itemId.value, "1111");
  const res = await sheep.$api.order.getUserScoreBookProduct({
    id: itemId.value,
  });
  mylist.value = res;
  console.log(mylist.value, "我的值");
};

const selected = ref([]); // 存储选中的项

// 切换选中状态
function toggleSelection(id) {
  const index = selected.value.indexOf(id);
  if (index === -1) {
    // 如果当前项未被选中，且选中的项数未超过限制，则添加到选中数组
    if (selected.value.length < maxSelection.value) {
      selected.value.push(id);
      console.log(selected.value);
    }
  } else {
    // 如果当前项已被选中，则从选中数组中移除
    selected.value.splice(index, 1);
  }
}

// 判断复选框是否禁用
function isDisabled(id) {
  // 如果当前项已被选中，或者选中的项数已达到最大限制，则禁用
  return (
    selected.value.length >= maxSelection.value && !selected.value.includes(id)
  );
}

const btn = async () => {
  console.log(selected.value);
  if (selected.value.length == 0) {
    uni.showToast({
      title: "请选择商品", // 提示内容
      icon: "none", // 不显示图标
      duration: 2000, // 提示框显示时长（毫秒）
    });
    return;
  }
  const productIdsString = selected.value.join(",");
  const fullAddress = `${ressInfo.value.province}${ressInfo.value.city}${ressInfo.value.district}${ressInfo.value.detailAddress}`;
  uni.showModal({
    title: "确认操作", // 弹框标题
    content: "确认提交订单吗？", // 弹框内容
    showCancel: true, // 是否显示取消按钮
    success: async (modalRes) => {
      if (modalRes.confirm) {
        console.log("用户点击了“确定”按钮");
        // 用户点击确定后，执行 insertScoreBookProduct 方法
        try {
          const res = await sheep.$api.order.insertScoreBookProduct({
            address: fullAddress,
            productIds: productIdsString,
            codeId: Id.value,
          });
          uni.showToast({
            title: "兑换成功", // 提示内容
            icon: "none", // 不显示图标
            duration: 2000, // 提示框显示时长（毫秒）
          });
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/user/wallet/giftbooklet",
            });
          }, 2000);

          console.log("订单提交成功", res);
          // 可以在这里处理成功后的逻辑，例如提示用户、跳转页面等
        } catch (error) {
          console.error("订单提交失败", error);
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/user/wallet/giftbooklet",
            });
          }, 2000);
          // 可以在这里处理失败后的逻辑，例如提示用户
        }
      } else if (modalRes.cancel) {
        console.log("用户点击了“取消”按钮");
        // 用户取消操作，不执行任何操作
      }
    },
  });
};
</script>
<style lang="scss" scoped>
.btnbox {
  position: absolute;
  bottom: 0;
  height: 140rpx;
  width: 100%;
  background-color: #fff;
  box-sizing: border-box;
  padding-top: 20rpx;
}
.list {
  height: 200rpx;
  background-color: #fff;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.btn {
  width: 150rpx;
  height: 80rpx;
  background-color: orange;
  margin-left: 560rpx;
  border-radius: 40rpx;
  line-height: 80rpx;
  color: #fff;
  text-align: center;
  font-size: 30rpx;
  font-weight: 700;
}
</style>
